<template>
  <fl-navBar
    dark
    :border="false"
    title="问卷填写"
    left-icon="left"
    color="#333333"
    :fixed="true"
    background-color="#fff"
    status-bar
  />
  <view class="questionList">
    <view class="questionTitle">{{ questionObj.questionnaireName }} </view>
    <view class="questionScore" v-if="questionObj.isScore === '1'">
      <text>填写人:{{ answerInfo.userName }} </text>
      <text>总得分:{{ questionObj.answerTotalScore }} </text>
    </view>
    <view class="questionItembox">
      <view
        class="questionItem"
        v-for="(ele, index) in questionObj.questionList"
        :key="ele.id"
      >
        <view class="question_name">
          <text class="question_index">{{ index + 1 }}.</text>
          <text class="question_con">{{ ele.questionName }}</text>
          <text class="question_me"
            >【{{ getDictLabelName(question_type, ele.questionType) }}】</text
          >
          <text class="question_type"
            >【{{ ele.isRequired === "0" ? "选填项" : "必填项" }}】</text
          >
          <text v-if="ele.questionType !== 'free'" class="question_score"
            >分数:{{ ele.questionScore }}分</text
          >
        </view>
        <view class="qu_list" v-if="ele.questionType === 'free'">
          <up-radio-group class="radio-label" v-model="ele.isSelect" placement="column">
            <view
              class="qu_listItem"
              v-for="(item, idx) in ele.questionContentList"
              :key="idx"
            >
              <up-radio
                :label="optionsIndex[idx] + '、' + item.content"
                :name="item.id"
              ></up-radio>
              <text v-if="isEdit" class="score-cls red-size">
                ({{ item.contentScore }}分)</text
              >
            </view>
          </up-radio-group>
          <view class="red-size rule-tips" v-if="redTips && !ele.isSelect &&  ele.isRequired === '1'">必填项不能为空</view>
        </view>
        <view class="qu_list" v-if="ele.questionType === 'single'">
          <up-radio-group class="radio-label" v-model="ele.isSelect" placement="column">
            <view
              class="qu_listItem"
              v-for="(item, idx) in ele.questionContentList"
              :key="idx"
            >
              <up-radio :label="optionsIndex[idx] + '、' + item.content" :name="item.id">
              </up-radio>
            </view>
          </up-radio-group>
          <view class="red-size rule-tips" v-if="redTips && !ele.isSelect &&  ele.isRequired === '1'">必填项不能为空</view>
        </view>
        <view class="qu_list" v-else-if="ele.questionType === 'multiple'">
          <up-checkbox-group v-model="ele.isSelect" placement="column">
            <view
              class="qu_listItem"
              v-for="(item, idx) in ele.questionContentList"
              :key="idx"
            >
              <up-checkbox
                :label="optionsIndex[idx] + '、' + item.content"
                :name="item.id"
              ></up-checkbox>
            </view>
          </up-checkbox-group>
          <view class="red-size rule-tips" v-if="redTips && !ele.isSelect &&  ele.isRequired === '1'">必填项不能为空</view>
        </view>
        <view class="qu_list" v-else-if="ele.questionType === 'question_answer'">
          <up-textarea v-model="ele.answerContent" placeholder=" "></up-textarea>
          <div class="red-size rule-tips" v-if="redTips && !ele.answerContent &&  ele.isRequired === '1'">必填项不能为空</div>
        </view>
        <view
          v-if="
            ele.questionType !== 'question_answer' && ele.isRight && ele.isRight !== ''
          "
          class="right_question"
        >
          正确答案: {{ ele.isRight }}
        </view>
      </view>
    </view>
    <view
      v-if="!isEdit"
      class="footerBtn"
      :style="{ paddingBottom: safeAreaInsets.bottom + 'px' }"
    >
      <button type="primary" @tap="submitpForm">提交</button>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useDict } from "@/utils/dict";
import {
  submitDataQuestionnaireAnswerRecord,
  getUserAnswerRecordDetail,
} from "@/api/surveyEvaluation/quesFilling";
import { getDictLabelName } from "@/utils/ruoyi";

import { navigateBack } from "@/utils/ruoyi";
const questionObj = ref({});
const answerInfo = ref({});
const hasQuestionAnswer = ref({});
const isEdit = ref(false);
import modal from "@/plugins/modal";
const { safeAreaInsets } = uni.getSystemInfoSync();
const optionsIndex = ref([
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
]);
const { question_type } = useDict("question_type");
const redTips = ref(false);
onLoad(() => {
  let curSur = uni.getStorageSync("curSur");
  if (curSur) {
    if (curSur.recordStatus !== "1" && curSur.questionStatus !== "2") {
      // 可以填写
      isEdit.value = false;
    } else {
      // 查看
      isEdit.value = true;
      getUserAnswer(curSur);
    }
    questionObj.value = curSur;
    console.log(questionObj.value);
  }
});
//获取填写人答题答案数据
function getUserAnswer(cForm) {
  const params = {
    recordId: cForm.recordId,
  };
  getUserAnswerRecordDetail(params).then((res) => {
    answerInfo.value = res.data;
    answerInfo.value.questionList.forEach((element) => {
      let selectedNodes = element.userQuestionContentList.filter(
        (i) => i.isSelect === "1"
      );
      let selectedIds = selectedNodes.map((i) => i.id);
      let selectRightNodes = element.userQuestionContentList.filter(
        (i) => i.isRight === "1"
      );
      let selectedRightContents = selectRightNodes.map((i) => i.content);
      let selectedRightIds = selectRightNodes.map((i) => i.id);
      if (element.questionType === "multiple") {
        element.isSelect = selectedIds.length === 1 ? [selectedIds[0]] : selectedIds;
      } else if (element.questionType === "single") {
        element.isSelect = selectedIds.length === 1 ? selectedIds[0] : selectedIds;
      }

      if (element.questionType === "free") {
        element.isSelect = selectedIds.length === 1 ? selectedIds[0] : "";
      }

      element.isRight =
        selectedRightContents.length > 0 ? selectedRightContents.join(",") : "";
      element.selectedRightIds =
        selectedRightIds.length === 1 ? [selectedRightIds[0]] : selectedRightIds;
      if (element.questionType === "multiple") {
        element.answerScore =
          element.selectedRightIds.join(",") === element.isSelect.join(",")
            ? element.questionScore
            : 0;
      }

      if (element.questionType === "single") {
        element.answerScore =
          element.selectedRightIds.length > 0 &&
          element.selectedRightIds[0] === element.isSelect
            ? element.questionScore
            : 0;
      }

      if (element.questionType === "question_answer") {
        element.answerContent = element.userQuestionContentList
          .map((i) => i.answerContent)
          .join(",");
      }
    });

    questionObj.value.questionList = answerInfo.value.questionList.map((item) => {
      return {
        ...item,
        ...{ questionContentList: item.userQuestionContentList },
      };
    });
    hasQuestionAnswer.value = questionObj.value.questionList.some(
      (i) => i.questionType === "question_answer"
    );
    questionObj.value.answerTotalScore = answerInfo.value.answerTotalScore;
    questionObj.value.isScore = answerInfo.value.isScore;
  });
}
//填写提交
async function submitpForm() {
  let requiredList = questionObj.value.questionList.filter((i) => i.isRequired === "1");
  if(requiredList.some(i => !i.isSelect && i.questionType !== "question_answer") || requiredList.some(i => !i.answerContent && i.questionType === "question_answer")){
    modal.msgError("必填项不能为空");
    redTips.value = true
    return;
  }
  const flag = await modal.confirm("确定要提交调查问卷吗？");
  if (!flag) return;
  const params = {
    questionnaireId: questionObj.value.id,
    questionList: questionObj.value.questionList.map((i) => {
      let isSelect = [];
      if (i.questionType === "single" && i.isSelect) {
        //单选题
        isSelect = [
          {
            contentId: i.isSelect,
          },
        ];
      } else if (i.questionType === "multiple" && i.isSelect && i.isSelect.length > 0) {
        //多选题
        isSelect = i.isSelect.map((item) => {
          return {
            contentId: item,
          };
        });
      } else if (i.questionType === "free" && i.isSelect) {
        //单选题
        isSelect = [
          {
            contentId: i.isSelect,
          },
        ];
      } else if (i.questionType === "question_answer") {
        //问答题
        isSelect = [{ answerContent: i.answerContent }];
      }
      return {
        questionId: i.id,
        answerList: isSelect,
      };
    }),
  };
  submitDataQuestionnaireAnswerRecord(params).then((res) => {
    modal.msgSuccess("操作成功");
    uni.$emit('load')
    setTimeout(() => {
      navigateBack();
    }, 200);
  });
}
</script>

<style lang="scss">
.right_question {
  color: #5ac725;
}
page {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.score-cls {
  color: red;
  font-size: 30rpx;
}
.radio-label {
  word-break: break-word; /* 允许长单词在任何位置换行 */
  white-space: normal; /* 确保文本正常换行 */
  display: block; /* 将元素设为块级元素，使其占满整行 */
  max-width: 100%; /* 限制标签的最大宽度 */
  font-size: 32rpx !important;
  span {
    font-size: 32rpx !important;
  }
}
.questionList {
  flex: 1;
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  background: #fff;
  .questionTitle {
    text-align: center;
    font-size: 34rpx;
    font-weight: 700;
    margin: 30rpx 0;
  }
  .questionScore {
    text-align: right;
    font-size: 32rpx;
    color: red;
    font-weight: 700;
    padding-right: 30rpx;
    text {
      padding-right: 30rpx;
    }
  }
  .questionItembox {
    width: 95%;

    margin: 0 auto;
    font-size: 30rpx;
    .questionItem {
      margin: 60rpx 0;
      .question_name {
        margin-bottom: 20rpx;
        .question_type {
          color: red;
        }
      }
      .qu_list {
        width: 95%;
        margin: 0 auto;
        .qu_listItem {
          padding: 20rpx;
          background-color: rgb(243, 243, 243);
          border-radius: 10rpx;
          border: 1rpx solid transparent;
          margin-bottom: 30rpx;
        }
        .activeQ {
          border: 1rpx solid #2979ff !important;
        }
      }
    }
  }
  .footerBtn {
    width: 95%;
    margin: 100rpx auto 20rpx;
  }
}

</style>
